package v1

import dai.core.base.Utils
import org.joml.Matrix4f
import org.joml.Vector3f

open class Camera(
    var fovy:Float = 60f,
    var near:Float = 0.1f,
    var far:Float = 1000f,
    val up : Vector3f = Vector3f(0f,1f,0f),
    val target:Obj = Obj(position = Vector3f(0f,0f,-1f))
) : Obj(){

    val viewMatrix = Matrix4f()
    val projMatrix = Matrix4f()

    // 临时变量
    val tmpVec3 = Vector3f()

    // app ref
    lateinit var app: GameApp

    fun init(gameApp: GameApp) {
        app = gameApp
    }

    fun updateProjMatrix(aspect: Float) {
        projMatrix.identity().perspective(Utils.toRadius(fovy), aspect, near, far)
    }

    fun updateViewMatrix() {
        viewMatrix.identity().lookAt(position, target.position, up)
    }

    // 沿相机自己的X轴移动amount
    fun translateX(amount:Float){
        val moved = tmpVec3.set(target.position).sub(position).normalize().cross(up).mul(amount)

        // y不变
        moved.y = 0f
        position.add(moved)
        target.position.add(moved)
    }

    // 沿相机自己的Z轴移动 amount
    fun translateZ(amount:Float){
        val moved = tmpVec3.set(position).sub(target.position).normalize().mul(amount)

        // y不变
        moved.y = 0f
        position.add(moved)
        target.position.add(moved)
    }

    fun translateY(amount: Float){
        position.y += amount
    }
}